import * as React from 'react';
import { withRouter,RouteComponentProps} from 'react-router';

import {connect} from 'react-redux';
import {getVerifyImg, loginRequest} from 'request/login';
import { TOKEN_NAME,SUCCESS_CODE,LOGIN_IMAGE_CODE } from 'constant/app';
import { IResult } from 'interface/app';
import {ILoginParams, ILoginImg, ILoginResult, IUserInfo} from 'interface/login';
import LoginPortal from 'component/portal/LoginPortal';
import { isEmpty } from 'util/stringutil';
import 'component/Login/index.css';
import loginImage from 'images/Login/login.jpg';
import css from 'component/Login/login.module.css';
import {md5} from "../../util/md5Util";
import lodash from 'lodash'
import {setUserInfo} from "../../redux/action/app";
export interface ILoginProps extends RouteComponentProps<any,any> {
    loginSuccessUri?:string,
    login?:()=>{},
    setUserInfo?(userInfo:IUserInfo):any
}

export interface ILoginState {
  isLoading:boolean,
  imgUrl:string,
  passError:string,
  userError:string,
  codeError:string,
  loginParams:ILoginParams
}

class Login extends React.Component<ILoginProps, ILoginState> {

  // username=React.createRef<HTMLInputElement>()
  // password=React.createRef<HTMLInputElement>()

  constructor(props: ILoginProps) {
    super(props);
    this.state = {
      isLoading:false,
      imgUrl:"",
      passError:'',
      userError:'',
      codeError:'',
      loginParams:{
        username:"",
        password:"",
        verifyCode:"",
        imgUUID:""
      }

    }
  }

  showLoading=()=>{
      this.setState({...this.state,isLoading:true})
  }

  hideLoading=()=>{
      this.setState({...this.state,isLoading:false})
  }


  beforeSubmit=()=>{
    if(isEmpty(this.state.loginParams.username)){
      this.setState({...this.state,userError:'用户名不能为空'})
      return false
    }
    if(isEmpty(this.state.loginParams.password)){
        this.setState({...this.state,passError:'密码不能为空'})
        return false
    }
    if(isEmpty(this.state.loginParams.verifyCode)){
        this.setState({...this.state,codeError:'验证码不能为空'})
      return false;
    }
    this.showLoading();
    return true
  }

  onSubmit=()=>{
    if(!this.beforeSubmit())return false;
    const loginParams=lodash.cloneDeep(this.state.loginParams)
    loginParams.password=md5(loginParams.password)
    loginRequest(loginParams,
        (data)=>{
                setTimeout(()=>{this.onResponse(data)},3000)
        },
        (data)=>{
            setTimeout(()=>{this.onResponse(data)},3000)
        })
  }

    componentDidMount() {
        this.getVerifyImgCode()
    }

    onResponse=(data:IResult)=>{
        this.hideLoading();
        const result:IResult=data;
        if(result.code!==SUCCESS_CODE){
            alert(result.msg)
            localStorage.removeItem(TOKEN_NAME);
            return;
        }
        const loginResult:ILoginResult=result.data


        localStorage.setItem(TOKEN_NAME,loginResult.token)
        this.props.setUserInfo(loginResult)
        this.props.history.push(this.props.loginSuccessUri as string)
  }

  onClear=()=>{
    const loginParams=lodash.cloneDeep(this.state.loginParams)
    loginParams.username=""
    loginParams.password=""
    loginParams.verifyCode=""
    this.setState({...this.state,userError:'',codeError:'',passError:'',loginParams})
  }

  setUsername=(event:any)=>{
      const value=event.target.value
      const loginParams=lodash.cloneDeep(this.state.loginParams)
      loginParams.username=value;
    this.setState({...this.state,loginParams,userError:isEmpty(value)?'用户名不能为空':''})
  }

  setPassword=(event:any)=>{
      const value=event.target.value
      const loginParams=lodash.cloneDeep(this.state.loginParams)
      loginParams.password=value;
    this.setState({...this.state,loginParams,passError:isEmpty(value)?'密码不能为空':''})
  }

  setVerifyCode=(event:any)=>{
      const value=event.target.value
      const loginParams=lodash.cloneDeep(this.state.loginParams)
      loginParams.verifyCode=value;
    this.setState({...this.state,loginParams,codeError:isEmpty(value)?'验证码不能为空':''})
  }

  getVerifyImgCode=()=>{
      getVerifyImg(LOGIN_IMAGE_CODE+"?"+new Date().getTime(),(result)=>{
          // const blob = new Blob([res.data]);
          // const imgUrl = window.URL.createObjectURL(blob);

          const loginImg:ILoginImg=result.data
          const imgUrl=loginImg.imgBase64;
          const imgUUID=loginImg.imgUUID;
          const loginParams=lodash.cloneDeep(this.state.loginParams)
          loginParams.imgUUID=imgUUID
          this.setState({...this.state,imgUrl,loginParams})

      },(result)=>{
          alert(result.msg)
      })
  }

  keyUp = (e) => {
    if (e.keyCode === 13) {
       this.onSubmit()
   }
}

  public render() {
    return (
      <div id="loginbox">
        {this.state.isLoading?<LoginPortal/>:null}

          <div id='outerbox'>
            <table id='logintable'>
                <thead>
                    <tr className='text-center'>
                        <th colSpan={2} className={"p-4"}>欢迎来到登陆页面！</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            <input onKeyUp={this.keyUp} onInput={this.setUsername} type="text" autoFocus className={`${css.input} ${this.state.userError?css.error:null}`} placeholder={"用户名"}  name='username' value={this.state.loginParams.username} />
                            <p className={"not-empty"}>{this.state.userError}&nbsp;</p>
                        </td>
                    </tr>
                    <tr>
                        <td colSpan={2}>
                            <input onKeyUp={this.keyUp} onInput={this.setPassword} type="password" className={`${css.input} ${this.state.passError?css.error:null}`} placeholder={"密码"}   name='password' value={this.state.loginParams.password} />
                            <p className={"not-empty"}>{this.state.passError}&nbsp;</p>
                        </td>
                    </tr>
                    <tr>
                        <td colSpan={2}>
                            <input onKeyUp={this.keyUp} onInput={this.setVerifyCode} type="text" className={`${css.input} ${this.state.codeError?css.error:null}`} placeholder={"验证码"}   name='verifycode' value={this.state.loginParams.verifyCode} />
                            <p className={"not-empty"}>{this.state.codeError}&nbsp;</p>
                        </td>
                    </tr>
                    <tr>
                        <td colSpan={2}>
                            <img className={"mb-2"}  src={this.state.imgUrl}  onClick={this.getVerifyImgCode} alt={""}/>
                        </td>
                    </tr>
                    <tr >
                        <td colSpan={2}  className='text-center'>
                            <button onClick={this.onSubmit}  type="button" className="btn btn-primary mx-5 mb-2">确定</button>
                            <button onClick={this.onClear}  type="button" className="btn btn-secondary mx-5 mb-2">清空</button>
                        </td>
                    </tr>
                </tbody>
            </table>
            <img id="loginimage" src={loginImage} alt={""}/>
          </div>
      </div>
    );
  }
}

const mapStateToProps=(state:any)=>{
    return state.app
}

const mapDispatchToProps={setUserInfo}
const WithConnect = connect(mapStateToProps,mapDispatchToProps)(Login)

export default withRouter(WithConnect)
